package io.kiki.sba.registry.common.model.store;

import lombok.Getter;

public final class CircuitBreakerStatistic {


    @Getter
    private final String group;

    @Getter
    private final String address;


    @Getter
    private final String ip;


    @Getter
    private volatile long failCount = 0;

    private volatile long lastFailTimeStamp;


    @Getter
    private volatile long consecutiveSuccess = 0;

    public CircuitBreakerStatistic(String group, String ip, String address) {
        this.group = group;
        this.ip = ip;
        this.address = address;
    }

    public CircuitBreakerStatistic(String group, String ip, String address, long failCount, long lastFailTimeStamp) {
        this.group = group;
        this.ip = ip;
        this.address = address;
        this.failCount = failCount;
        this.lastFailTimeStamp = lastFailTimeStamp;
    }

    public synchronized void success(int threshold) {
        consecutiveSuccess++;
        if (consecutiveSuccess >= threshold) {
            failCount = 0;
            lastFailTimeStamp = 0;
        }
    }

    public synchronized void fail() {
        failCount++;
        lastFailTimeStamp = System.currentTimeMillis();
        consecutiveSuccess = 0;
    }

    public boolean circuitBreak(int failThreshold, long silenceMillis) {

        return failCount > failThreshold && System.currentTimeMillis() < lastFailTimeStamp + silenceMillis;
    }


}
